package com.yangtao.prototype.system.login.web;

import com.yangtao.framework.common.SystemConstant;
import com.yangtao.framework.service.ServiceLocator;
import com.yangtao.framework.util.CookieUtil;
import com.yangtao.framework.util.Struts2Utils;
import com.yangtao.framework.web.struts2.BaseAction;
import com.yangtao.prototype.system.login.service.LoginService;
import org.apache.commons.lang.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class LoginAction extends BaseAction<LoginModel, LoginService> {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public String login() throws Exception {
		// 验证用户是否合法，如果合法，进入登陆页面
		model.setClientIp(request.getRemoteAddr());
		model.setClientAddr(request.getRemoteHost());
		service.login(model);
		if (hasError()) {
			formatMessage();
			return "login";
		}
		// 将用户信息保存在cookie中
		CookieUtil.setCookie(response, SystemConstant.Y_SESSIONID, model.getSessionId());
//		session.setAttribute(SystemConstant.LOG_ID, model.getLn().getId());
		return "layout";
	}

	/**
	 * 查看当前在线用户
	 */
	public String online() {
		model = service.getOnLineUser(model);
		return render("onlineUserList");
	}

	/**
	 * 登出
	 */
	public String logOut() {
		JedisPool pool = ServiceLocator.getInstance().getService(JedisPool.class);
		Jedis client = pool.getResource();
		String logId = client.hget(model.getSessionId(), SystemConstant.LOG_ID);
		if (StringUtils.isNotEmpty(logId)) {
			model.setLogId(logId);
			service.changeLogNote(model);
		}
		// 使用户失效
		client.expire(model.getSessionId(), 0);
		pool.returnResource(client);
		return "login";
	}

	/**
	 * 查询登陆日志
	 *
	 * @return
	 */
	public String lognote() {
		return render("LogNoteQuery");
	}

	/**
	 * 查询登陆日志列表
	 */
	public String lognoteList() {
		service.findLogs(model);
		Struts2Utils.renderJson(model.getPage());
		return null;
	}
}
